<template>
    <div>
      <el-dialog
        v-model="createVisible"
        :title="operation == 'create' ? '添加插件' : '编辑插件'"
        @before-ok="createOk"
        @close="close(createRef)"
        width="600px"
        top="100px"
      >
        <div style="width:450px">
          <el-form
            :model="createForm"
            ref="createRef"
            :rules="createRules"
            label-width="120px"
            size="default"
            v-loading="createLoading"
          >
            <el-form-item label="插件名称：" prop="title">
              <el-input v-model="createForm.title" placeholder="请输入插件名称"></el-input>
            </el-form-item>
            <el-form-item label="插件标识：" prop="addon_name">
              <el-input v-model="createForm.addon_name" placeholder="请输入插件标识"></el-input>
            </el-form-item>
            <el-form-item label="插件版本：" prop="version">
              <el-input-number
                    v-model="createForm.version"
                    :min="0.1"
                    :step="0.1"
                    controls-position="right"
                />
            </el-form-item>
            <el-form-item label="描述：" prop="desc">
              <el-input v-model="createForm.desc" placeholder="请输入描述"></el-input>
            </el-form-item>
            
            <el-form-item
              label="模块："
              prop="type"
            >
              <el-radio-group v-model="createForm.type">
                <template v-for="(item,index) in TypeEnum" :key="index">
                  <el-radio :label="item.value" size="default" border>{{ item.name }}</el-radio>
                </template>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="图标：" prop="icon">
              <el-input v-model="createForm.icon" placeholder="图标">
                <template #append>
                  <el-button
                    @click="
                      () => {
                        selectModalIconRef.open();
                      }
                    "
                  >
                    选择图标
                  </el-button>
                  <select-icon-modal
                    ref="selectModalIconRef"
                    @change="iconChange"
                  ></select-icon-modal>
                </template>
            </el-input>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="flex center">
            <el-button @click="createVisible = false">取消</el-button>
            <el-button type="primary" :loading="btnLoading" :disabled="btnLoading" @click="createOk(createRef)"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
<script lang="ts">
  export default {
    name:'systemAddonCreate'
  }
</script>
<script lang="ts" setup>
  import { ref, getCurrentInstance, nextTick, reactive } from "vue";
  import {  useConfig } from "@/store";
  import type { CommonProps, FormInstance, FormRules } from "element-plus";
  import { create, update,getDetail } from "@/api/system/addon";
  import type { Result, ResultError } from "@/types";
  
  const {
    proxy: { $utils },
  } = getCurrentInstance() as any;
  
  const emit = defineEmits(["success"]);
  
  const operation = ref("create");
  
  const operationId = ref(0);
  
  const createVisible = ref(false);
  
  const createRef: any = ref<typeof FormInstance>();
  
const selectModalIconRef = ref<any>();

  const createForm = ref({
    title: "",
    addon_name: "",
    version: "",
    desc: "",
    icon: "",
    type:0
  });
  
  const createRules: any = reactive({
    title: [{ required: true, message: "插件名称不能为空！", trigger: 'blur' }],
    addon_name: [{ required: true, message: "插件标识不能为空！" , trigger: 'blur'}],
  });

const TypeEnum = ref(useConfig().getEnumItem("system.addon.TypeEnum"));
  
  const createLoading: any = ref(false);
  
  const toInit = () => {
    if (!operationId.value) {
      return;
    }
    getDetail({id:operationId.value})
      .then((res:Result) => {
        createForm.value.title = res.data.title;
        createForm.value.addon_name = res.data.addon_name;
        createForm.value.version = res.data.version;
        createForm.value.icon = res.data.icon;
        createForm.value.desc = res.data.desc;
        createForm.value.type = res.data.type.value;
      })
      .catch((err:ResultError) => {
        $utils.errorMsg(err);
      });
  };
  
  const btnLoading = ref(false)
  
    const iconChange = (icon: string) => {
    createForm.value.icon = icon;
    };

  const createOk = async (formEl:typeof FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid:any, fields: any) => {
      if (valid) {
        if(btnLoading.value){
          return
        }
        btnLoading.value = true
        let operationApi: any = null;
        if (operation.value == "create") {
          operationApi = create(createForm.value);
        } else {
          operationApi = update(
            Object.assign(
              {
                id: operationId.value,
              },
              createForm.value
            )
          );
        }
        operationApi
          .then((res:Result) => {
            $utils.successMsg(res.message);
            close(formEl);
            emit("success");
            btnLoading.value = false
          })
          .catch((err:ResultError) => {
            $utils.errorMsg(err);
            btnLoading.value = false
          });
      }
    });
  };
  
  const open = (id = 0) => {
    if (id != 0) {
      operation.value = "update";
      operationId.value = id;
    } else {
      operation.value = "create";
    }
    nextTick(() => {
      toInit();
    });
    createVisible.value = true;
  };
  
  const close = async (formEl:typeof FormInstance | undefined) => {
    if (formEl) {
      formEl.resetFields();
    }
    operationId.value = 0;
    createVisible.value = false;
  };
  
  defineExpose({ open });
  </script>